﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        System.Threading.Mutex mutex;

        public App()
        {
            this.Startup += new StartupEventHandler(App_Startup);
        }

        static App()
        {
            configManager = new XmlConfigManager(Globals.PathOfUserFolder + "config.xml");
            //workspaceConfigManager 是可以变化的，不需要在这里初始化。
        }

        void App_Startup(object sender, StartupEventArgs e)
        {
            var unableDoubleInstanceText = App.ConfigManager.Get("UnableDoubleInstance");
            if (string.IsNullOrWhiteSpace(unableDoubleInstanceText) || unableDoubleInstanceText.ToLower() == "true")
            {
                bool ret;
                mutex = new System.Threading.Mutex(true, Globals.AppName, out ret);

                if (!ret)
                {
                    MessageBox.Show("　　已有一个程序实例运行！双开应用程序较容易造成正在编辑的文件版本混乱。\r\n　　实在需要双开，请点击主界面【偏好】→【禁止双开应用程序】菜单项来解除限制。", Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                    //这里不能用LMessageBox.Show()方法。因为该方法对主窗口有依赖性。

                    Environment.Exit(0);
                }
            }
        }

        private static bool unableDoubleInstance = true;
        /// <summary>
        /// 禁止应用程序双开。
        /// </summary>
        public static bool UnableDoubleInstance
        {
            get { return unableDoubleInstance; }
            set { unableDoubleInstance = value; }
        }

        private static XmlConfigManager configManager;
        /// <summary>
        /// 用于保存配置的Xml配置管理器。
        /// </summary>
        public static XmlConfigManager ConfigManager
        {
            get { return configManager; }
        }

        private static XmlConfigManager workspaceConfigManager = null;
        /// <summary>
        /// 工作区配置文件管理器。
        /// </summary>
        public static XmlConfigManager WorkspaceConfigManager
        {
            get
            {
                if (workspaceConfigManager == null)
                {
                    workspaceConfigManager = new XmlConfigManager(Globals.PathOfWorkspace + "Configure.xml");
                }

                return workspaceConfigManager;
            }
            set { workspaceConfigManager = value; }
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (e.Args.Length > 0)
            {
                if (e.Args[0].Contains(' '))
                {
                    Globals.CmdParameterString = "\"" + e.Args[0] + "\"";
                }
                else Globals.CmdParameterString = e.Args[0];
            }
            else Globals.CmdParameterString = "";
        }
    }
}
